//
//  ReamlDataTool.m
//  sanda
//
//  Created by wsj2015 on 16/10/25.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "ReamlDataTool.h"
#import <Realm/Realm.h>

static ReamlDataTool *realmTool = nil;
@implementation ReamlDataTool

+ (instancetype)sharedTool{

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        realmTool = [[ReamlDataTool alloc] init];
    });
    return realmTool;
}



- (void)addNewCourse:(HELCourseDetailModel *)course{
 
    if (!course) {
        return;
    }
   
    HELCompulsoryM * relmCourse =[HELCompulsoryM realmFromCourse:course];
    RLMRealm *realm = [RLMRealm defaultRealm];
    [realm transactionWithBlock:^{
        [realm addObject:relmCourse];
    }];
   
}

- (RLMResults *)allObjects{
   
    RLMRealm *realm =[RLMRealm defaultRealm];
    return [HELCompulsoryM allObjectsInRealm:realm];
    
}

- (void)updateCourseWithCourse:(HELCourseDetailModel*)course{
    // Query and update the result in another thread
    dispatch_async(dispatch_queue_create("background", 0), ^{
        HELCompulsoryM *oldcourse =[[HELCompulsoryM objectsWhere:[NSString stringWithFormat:@"id == %i",[course.id integerValue]] ] firstObject];
        if (oldcourse) {
             RLMRealm *realm = [RLMRealm defaultRealm];
            [realm beginWriteTransaction];
            [oldcourse updateWithCourse:course];
            [realm commitWriteTransaction];
            
        }else{
            [self addNewCourse:course];
        }
    });
   
}
- (void)deleCourseWithCourses:(NSArray <HELCourseDetailModel*>*)array{
    RLMRealm *realm = [RLMRealm defaultRealm];
    [realm beginWriteTransaction];
    [realm deleteObjects:array];
    [realm commitWriteTransaction];


    
}

- (void)configWithConfig:(NSString*)userAccout{
    if (!userAccout) {
        return;
    }
    NSArray *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [docPath objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"sanda_%@",userAccout]];
    NSLog(@"数据库目录 = %@",filePath);
    
    RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
    config.fileURL = [NSURL URLWithString:filePath];
    
    config.readOnly = NO;
    int currentVersion = 1.0;
    config.schemaVersion = currentVersion;
    
    config.migrationBlock = ^(RLMMigration *migration , uint64_t oldSchemaVersion) {
        // 这里是设置数据迁移的block
        if (oldSchemaVersion < currentVersion) {
        }
    };
    
    [RLMRealmConfiguration setDefaultConfiguration:config];}

@end
